package com.ja.openchat.ui.chat.group;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.lifecycle.ViewModelProviders;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityGroupInviteLinkBinding;
import com.ja.openchat.viewmodels.GroupInviteLinkViewModel;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.ChatInviteLink;
import com.zy.openchat.core.model.group.SuperGroupFullInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.util.share.GoShare;

import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

public class GroupInviteLinkActivity extends BaseActivity<ActivityGroupInviteLinkBinding, GroupInviteLinkViewModel> implements View.OnClickListener {

//    @BindView(R.id.invite_link_text)
//    SDAdaptiveTextView invite_link_text;
//    @BindView(R.id.reset_link_btn)
//    View reset_link_btn;
//    @BindView(R.id.clean_link_btn)
//    View clean_link_btn;

    public static void start(Activity activity, ChatInfo chat,SuperGroupFullInfo superGroupFullInfo,boolean canEditGroupSetting) {
        Intent intent = new Intent();
        intent.setClass(activity, GroupInviteLinkActivity.class);
        intent.putExtra("chat", chat);
        intent.putExtra("superGroupFullInfo",superGroupFullInfo);
        intent.putExtra("canEditGroupSetting",canEditGroupSetting);
        activity.startActivity(intent);
    }
    private SuperGroupFullInfo superGroupFullInfo;
    private ChatInfo chatInfo;
    private boolean canEditGroupSetting;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_group_invite_link;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public GroupInviteLinkViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(GroupInviteLinkViewModel.class);
    }

    @Override
    public void initView() {
        super.initView();
        binding.toolbar.tvBarTitle.setText(getString(R.string.group_invitation_link));
        if(getIntent()==null||getIntent().getParcelableExtra("superGroupFullInfo")==null||getIntent().getParcelableExtra("chat")==null){
            finish();
            return;
        }
        chatInfo = (ChatInfo)getIntent().getParcelableExtra("chat");
        superGroupFullInfo = (SuperGroupFullInfo)getIntent().getParcelableExtra("superGroupFullInfo");
        canEditGroupSetting = getIntent().getBooleanExtra("canEditGroupSetting",false);
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.copyLinkBtn.setOnClickListener(this);
        binding.resetLinkBtn.setOnClickListener(this);
        binding.shareLinkBtn.setOnClickListener(this);
        binding.cleanLinkBtn.setOnClickListener(this);

        binding.resetLinkBtn.setVisibility(canEditGroupSetting?View.VISIBLE:View.GONE);
        binding.cleanLinkBtn.setVisibility(canEditGroupSetting?View.VISIBLE:View.GONE);

//        if(canEditGroupSetting&&superGroupFullInfo!=null&& TextUtils.isEmpty(superGroupFullInfo.invite_link)){
//            genrateLink();
//        }
        resetUi();
    }

    private void genrateLink(){
        TelegramManager.getTelegramManager().generateChatInviteLink(this, chatInfo.id, new TgResultBlock<ChatInviteLink>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, ChatInviteLink obj) {
                if(obj!=null){
                    superGroupFullInfo.invite_link = obj.invite_link;
                }
                resetUi();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void cleanLink(){
        showProgress();
        TelegramManager.getTelegramManager().disableInviteLink(this, chatInfo.id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null&&obj.ok){
                    superGroupFullInfo.invite_link = "";
                }
                resetUi();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void resetUi(){
        if(superGroupFullInfo!=null&&!TextUtils.isEmpty(superGroupFullInfo.invite_link)){
            binding.inviteLinkText.post(new Runnable() {
                @Override
                public void run() {
                    binding.inviteLinkText.setAdaptiveText(superGroupFullInfo.invite_link);
                }
            });
        }else{
            binding.inviteLinkText.setText(getString(R.string.reset_invite_link));
        }
    }

   public void onClick(View view) {
        switch (view.getId()) {
            case R.id.copy_link_btn:
                if(superGroupFullInfo!=null&&!TextUtils.isEmpty(superGroupFullInfo.invite_link)){
                    ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    if (clipboardManager != null) {
                        ClipData clipData = ClipData.newPlainText("copyContent", superGroupFullInfo.invite_link);
                        clipboardManager.setPrimaryClip(clipData);
                        ToastUtils.showShort(getString(R.string.copied_text));
                    }
                }else{
                    showErrorTip(getString(R.string.group_link_not_set_to_reset));
                }

                break;
            case R.id.clean_link_btn:
                cleanLink();
                break;
            case R.id.reset_link_btn:
                genrateLink();
                break;
            case R.id.share_link_btn:
                if(superGroupFullInfo!=null&&!TextUtils.isEmpty(superGroupFullInfo.invite_link)&&chatInfo!=null){
                    new GoShare.FShareBuilder(this, App.getInstanse().getPackageName() + ".utilcode.fileprovider")
                            .setShareSubject(getResources().getString(R.string.app_name))
                            .setTopTitle(getString(R.string.group_invitation))
                            .setShareContent(String.format(getString(R.string.click_join_group),chatInfo.title)+ superGroupFullInfo.invite_link)
                            .build()
                            .shareByCustom();
                }else{
                    showErrorTip(getString(R.string.group_link_not_set_to_reset));
                }

                break;
        }
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
}
